package  
{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.external.ExternalInterface;
	import flash.net.SharedObject;
	import flash.events.NetStatusEvent;
	import flash.system.Security;
    import flash.net.SharedObjectFlushStatus;
	import flash.display.LoaderInfo;
	/**
	 * ...
	 * @author egoing
	 */
	public class Cookie extends MovieClip
	{
		
		private var so:SharedObject;
		private var _id:String;
		public function Cookie() 
		{
			Security.allowDomain('*');
			var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
			_id = paramObj.id == undefined ? 'monkeyFly' : paramObj.id;
			addEventListener(Event.ADDED_TO_STAGE, function(e:Event) {
				if (ExternalInterface.available) {
					ExternalInterface.addCallback('setValue', setValue);
					ExternalInterface.addCallback('getValue', getValue);
				}
				so = SharedObject.getLocal(_id);
				//setValue('test');
				if (so.data.cookie == undefined) {
					so.data.cookie = new Object();
				}
			} );
		}
		
		private function setValue(name:String, value:Object) {
			so.data.cookie[name] = value;
            var flushStatus:String = null;
            try {
                flushStatus = so.flush(10000);
            } catch (error:Error) {
                trace("Error...Could not write SharedObject to disk\n");
            }
            if (flushStatus != null) {
                switch (flushStatus) {
                    case SharedObjectFlushStatus.PENDING:
                        trace("Requesting permission to save object...\n");
                        so.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
                        break;
                    case SharedObjectFlushStatus.FLUSHED:
                        trace("Value flushed to disk.\n");
                        break;
                }
            }
		}
		
		private function getValue(name:String):Object {
			try{
				return so.data.cookie[name];
			} catch (e:Error) {
				trace(e);
				return true;
			}
			return true;
		}
		
		private function clear():void {
            delete so.data.cookie;
        }
		
		private function onFlushStatus(event:NetStatusEvent):void {
            trace("User closed permission dialog...\n");
            switch (event.info.code) {
                case "SharedObject.Flush.Success":
                    trace("User granted permission -- value saved.\n");
                    break;
                case "SharedObject.Flush.Failed":
                    trace("User denied permission -- value not saved.\n");
                    break;
            }
            trace("\n");

            so.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
        }

	}
	
}